package com.longxi.tianjintianbao.ui.presenter.task;

import android.content.Intent;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SelectTaskListListener;
import com.longxi.tianjintianbao.model.ProgressLabel;
import com.longxi.tianjintianbao.model.task.Task;
import com.longxi.tianjintianbao.model.task.TaskProgress;
import com.longxi.tianjintianbao.ui.activity.main.MainActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.ProgressLabelViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.TaskListViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.TaskProgressViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.dialog_fragment.TaskExplainDialogFragment;
import com.longxi.tianjintianbao.ui.dialog_fragment.TaskProgressDialogFragment;
import com.longxi.tianjintianbao.ui.view.task.ITaskDetailAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 70339 on 2018/5/3.
 * 代码无八阿哥
 * 阿弥陀佛
 */
public class TaskDetailAtPresenter extends BasePresenter<ITaskDetailAtView> {
    private MultiTypeAdapter adapter;
    private Items items;

    private Task task;
    private String billid;
    private boolean noShowBtn;

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(Task.class, new TaskListViewBinder(listener));
            adapter.register(ProgressLabel.class, new ProgressLabelViewBinder());
            adapter.register(TaskProgress.class, new TaskProgressViewBinder());
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        billid = intent.getStringExtra(AppConst.BILLID);
        noShowBtn = intent.getBooleanExtra(AppConst.STATE, false);

        mContext.setTitle("任务详情");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    //将列表页的数据展示
    public void setTask(){
        mContext.showLoading();
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getTask(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Task>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.showError();
            }

            @Override
            public void onNext(HttpResult<Task> result) {
                if(result.getCode() != 0){
                    mContext.showError();
                    return;
                }

                if(result.getData().size() == 0){
                    mContext.showNoData();
                    return;
                }

                mContext.hideLoading();

                task = result.getData().get(0);

                items = new Items();
                items.add(task);
                items.add(new ProgressLabel("任务", task.getState()));
                adapter.setItems(items);
                adapter.notifyDataSetChanged();

                getTaskProgress();

                showBtn();
            }
        });
    }

    //获取任务进度
    public void getTaskProgress(){
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getTaskProgress(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<TaskProgress>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<TaskProgress> result) {
                Collections.reverse(result.getData());
                items.addAll(result.getData());
                adapter.setItems(items);
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void showBtn(){
        if(noShowBtn){
            return;
        }

        switch (task.getState()) {
            case "未接单":
                getView().getLlState().setVisibility(View.VISIBLE);
                getView().getLlCannot().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setText("立即接单");
                break;
            case "已接单":
                getView().getLlState().setVisibility(View.VISIBLE);
                getView().getLlCannot().setVisibility(View.VISIBLE);
                getView().getBtnPause().setVisibility(View.VISIBLE);
                getView().getBtnPause().setText("添加工作进展");
                getView().getBtnComplete().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setText("确认完成");
                break;
            default:
                getView().getLlState().setVisibility(View.GONE);
                break;
        }
    }

    public void btnComplete(){
        switch (task.getState()) {
            case "未接单":
                acceptTask("1", "");
                break;
            case "已接单":
                addTaskProgress("确认工作完成");
                break;
        }
    }

    public void acceptTask(String state, String explain){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", task.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
            object.put("state", state);
            object.put("explain", explain);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().acceptTask(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                MyUtils.showToast(result.getMsg());

                if("1".equals(state)){
                    addTaskProgress("接单,开始工作");
                    return;
                }

                mContext.setResult(mContext.RESULT_OK);
                setTask();
            }
        });
    }

    public void addTaskProgress(String content){
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", task.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
            object.put("content", content);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().addTaskProgress(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                MyUtils.showToast("添加进度成功");
                if(taskProgressDialogFragment != null){
                    taskProgressDialogFragment.dismiss();
                }
                if("确认工作完成".equals(content)){
                    acceptTask("2", "");
                    return;
                }
                setTask();
            }
        });
    }

    public TaskDetailAtPresenter(BaseActivity context) {
        super(context);
    }

    TaskExplainDialogFragment taskExplainDialogFragment;
    public void showTaskExplainDialogFragment() {
        taskExplainDialogFragment = new TaskExplainDialogFragment();
        taskExplainDialogFragment.show(mContext.getFragmentManager(), "TaskExplainDialogFragment");
    }

    TaskProgressDialogFragment taskProgressDialogFragment;
    public void showTaskProgressDialogFragment() {
        taskProgressDialogFragment = new TaskProgressDialogFragment();
        taskProgressDialogFragment.show(mContext.getFragmentManager(), "TaskExplainDialogFragment");
    }

    SelectTaskListListener listener = new SelectTaskListListener() {
        @Override
        public void onSuccess(Task task) {

        }
    };
}
